package com.outfood.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.outfood.common.common.Result;
import com.outfood.config.PythonServerConfig;
import com.outfood.config.WxConfig;
import com.outfood.domain.*;
import com.outfood.mapper.StoreMapper;
import com.outfood.service.*;
import com.outfood.task.AutoReLoginTask;
import com.outfood.utils.RedisUtil;
import com.outfood.utils.UuidUtils;
import com.ruoyi.common.exception.BusinessException;
import com.rys.common.enums.SearchTypeEnum;
import com.rys.common.utils.DateUtils;
import com.rys.common.utils.Search;
import com.rys.framework.service.base.BaseServcie;
import com.tps.open.mq.enums.QueueEnums;
import com.tps.open.weixin.dto.XcxUnifiedorderDTO;
import com.tps.open.weixin.open.XcxUnifiedorderService;
import com.tps.open.weixin.vo.UnifiedorderAttachVO;
import com.tps.open.weixin.vo.XcxPayPramsVO;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Author huisonglin
 * @Description
 * @PackageName outfood-platform
 * @Package com.outfood.service.impl
 * @Date 2024-03-25 17:05
 * @Version 1.0
 */
@Log4j2
@Service
public class StoreServiceImpl extends BaseServcie<Store> implements IStoreService {

    @Resource
    RestTemplate restTemplate;
    @Resource
    IStoreService storeService;
    @Resource
    IUserStoreRelationService userStoreRelationService;

    @Resource
    IRuleService ruleService;

    @Resource
    MeiTuanOperateServiceImpl meiTuanOperateService;

    @Reference
    XcxUnifiedorderService xcxUnifiedorderService;

    @Resource
    IUserService userService;
    @Resource
    WxConfig wxConfig;


    @Resource
    IRechargeRecordService rechargeRecordService;

    public XcxPayPramsVO renew(Long storeId, Integer month,Long userId,String price){
        User user = userService.get(userId);
        /**
         * 创建订单
         */
        RechargeRecord rechargeRecord = new RechargeRecord();
        rechargeRecord.setPrice(price);
        rechargeRecord.setMonth(month+"");
        rechargeRecord.setStatus("0");
        rechargeRecord.setUserId(userId);
        rechargeRecord.setStoreId(storeId);
        rechargeRecord.setOrderNo(new Date().getTime()+"");
        rechargeRecordService.add(rechargeRecord,userId+"");

        XcxUnifiedorderDTO xcxUnifiedorderDTO = new XcxUnifiedorderDTO();
        xcxUnifiedorderDTO.setOpenid(user.getOpenId());
        //xcxUnifiedorderDTO.setOpenid("o7rfE5PFD2m54dlQqsjdAdkjwo0E");
        xcxUnifiedorderDTO.setBody("续费");
        xcxUnifiedorderDTO.setDetail("续费");
        xcxUnifiedorderDTO.setNonce_str(UuidUtils.get32UUID());

        xcxUnifiedorderDTO.setOut_trade_no(rechargeRecord.getOrderNo());
        xcxUnifiedorderDTO.setSpbill_create_ip("36.5.113.204");
        xcxUnifiedorderDTO.setTotal_fee(new BigDecimal(price));
        xcxUnifiedorderDTO.setAppid(wxConfig.getWxAppid());
        xcxUnifiedorderDTO.setMch_id(wxConfig.getWxMchId());
//        xcxUnifiedorderDTO.setProfit_sharing("Y"); //不分账
        //v3证书TfV7pfyzr5JI9t20sxwy0Sp0U7J6CTAc   v2 TfV7pfyzr5JI9t20sxwy0Sp0U7J6CTAe
        xcxUnifiedorderDTO.setKey(wxConfig.getWxKey());
        xcxUnifiedorderDTO.setNotify_url("http://notify.huisonglin.top/notify/accpet");
        xcxUnifiedorderDTO.setTrade_type("JSAPI");
        unifiedorderAttachVOPro unifiedorderAttachVO = new unifiedorderAttachVOPro();
        unifiedorderAttachVO.setApikey(wxConfig.getWxKey());
        unifiedorderAttachVO.setTargetQueue(QueueEnums.OUTFOOD_ADMIN.toString());
        unifiedorderAttachVO.setHandlerBeanName("xcxPayNotifyCusmerHander");
        xcxUnifiedorderDTO.setAttach(JSON.toJSONString(unifiedorderAttachVO));
        XcxPayPramsVO unifiedorder = xcxUnifiedorderService.unifiedorder(xcxUnifiedorderDTO);
        return unifiedorder;
    }

    @Override
    public void loginByQrCode(String ksid, String shopId, String shopName, Long userId) {
        List<Store> storeList = storeService.getList(new Search().add("regionId", SearchTypeEnum.EqualTo, shopId));
        if(CollectionUtils.isEmpty(storeList)){
            log.info("登录成功，开始进行逻辑处理");
            Store store = new Store();
            store.setCookie(ksid);

            store.setStoreName(shopName);
            store.setRegionId(shopId);
            store.setPlatform("ELEME");
            store.setExpireTime(DateUtils.addDays(new Date(),3)); //设置2天有效期
            store.setOnlineStatus("ONLINE"); //设置为在线状态
            store.setStoreStatus("1");
            storeService.add(store,userId+"");

            UserStoreRelation userStoreRelation = new UserStoreRelation();
            userStoreRelation.setUserId(userId);
            userStoreRelation.setStoreId(store.getId());
            userStoreRelationService.add(userStoreRelation,userId+"");

            Rule rule = new Rule();
            rule.setStoreId(store.getId());
            rule.setTime(4); //默认四分钟后出餐
            ruleService.add(rule,userId+"");
            meiTuanOperateService.upNotice(store.getId());
        }else{
            Store store = storeList.get(0);
            Store isexsit = getStore(userId, store.getId());
            if(isexsit == null){
                UserStoreRelation userStoreRelation = new UserStoreRelation();
                userStoreRelation.setUserId(userId);
                userStoreRelation.setStoreId(store.getId());
                userStoreRelationService.add(userStoreRelation,userId+"");
            }
            store.setCookie(ksid);
            store.setStoreName(shopName);
            store.setRegionId(shopId);
            store.setOnlineStatus("ONLINE"); //设置为在线状态
            store.setStoreStatus("1");
            storeService.update(store.getId(),store,userId+"");
            meiTuanOperateService.upNotice(store.getId());
        }


    }

    @Resource
    PythonServerConfig pythonServerConfig;
    //密码登录
    @Override
    public void loginByQrCode(String ksid, String shopId, String shopName, Long userId, String username, String password) {
        List<Store> storeList = storeService.getList(new Search().add("regionId", SearchTypeEnum.EqualTo, shopId));
        Store store = null;
        if(CollectionUtils.isEmpty(storeList)){
            log.info("登录成功，开始进行逻辑处理");
            store = new Store();
            store.setCookie(ksid);

            store.setStoreName(shopName);
            store.setRegionId(shopId);
            store.setPlatform("ELEME");
            store.setUsername(username);
            store.setPassword(password);
            store.setServerId(pythonServerConfig.getServerId());
            store.setExpireTime(DateUtils.addDays(new Date(),3)); //设置2天有效期
            store.setOnlineStatus("ONLINE"); //设置为在线状态
            store.setStoreStatus("1");
            storeService.add(store,userId+"");

            UserStoreRelation userStoreRelation = new UserStoreRelation();
            userStoreRelation.setUserId(userId);
            userStoreRelation.setStoreId(store.getId());
            userStoreRelationService.add(userStoreRelation,userId+"");

            Rule rule = new Rule();
            rule.setStoreId(store.getId());
            rule.setTime(4); //默认四分钟后出餐
            ruleService.add(rule,userId+"");
            meiTuanOperateService.upNotice(store.getId());
        }else{
            store = storeList.get(0);
            Store isexsit = getStore(userId, store.getId());
            if(isexsit == null){
                UserStoreRelation userStoreRelation = new UserStoreRelation();
                userStoreRelation.setUserId(userId);
                userStoreRelation.setStoreId(store.getId());
                userStoreRelationService.add(userStoreRelation,userId+"");
            }
            store.setOnlineStatus("ONLINE"); //设置为在线状态
            store.setCookie(ksid);
            store.setStoreName(shopName);
            store.setServerId(pythonServerConfig.getServerId());
            store.setUsername(username);
            store.setPassword(password);
            store.setRegionId(shopId);
            storeService.update(store.getId(),store,userId+"");
            meiTuanOperateService.upNotice(store.getId());
        }
        if(store != null){
            ElmeOperateServiceImpl.Query query = new ElmeOperateServiceImpl.Query();
            query.setShopId(store.getRegionId());
            query.setKsid(store.getCookie());
            query.setStoreId(store.getId());
            elmeOperateService.getAccessToken(query);
        }

    }


    @Override
    public void loginByQrCode(String ksid, String shopId, String shopName, Long userId, String mobile) {
        List<Store> storeList = storeService.getList(new Search().add("regionId", SearchTypeEnum.EqualTo, shopId));
        Store store = null;
        if(CollectionUtils.isEmpty(storeList)){
            log.info("登录成功，开始进行逻辑处理");
            store = new Store();
            store.setCookie(ksid);

            store.setStoreName(shopName);
            store.setRegionId(shopId);
            store.setPlatform("ELEME");
            store.setMobile(mobile);
            store.setExpireTime(DateUtils.addDays(new Date(),3)); //设置2天有效期
            store.setOnlineStatus("ONLINE"); //设置为在线状态
            store.setStoreStatus("1");
            store.setServerId(pythonServerConfig.getServerId());
            storeService.add(store,userId+"");

            UserStoreRelation userStoreRelation = new UserStoreRelation();
            userStoreRelation.setUserId(userId);
            userStoreRelation.setStoreId(store.getId());
            userStoreRelationService.add(userStoreRelation,userId+"");

            Rule rule = new Rule();
            rule.setStoreId(store.getId());
            rule.setTime(4); //默认四分钟后出餐
            ruleService.add(rule,userId+"");
            meiTuanOperateService.upNotice(store.getId());
        }else{

            store = storeList.get(0);
            Store isexsit = getStore(userId, store.getId());
            if(isexsit == null){
                UserStoreRelation userStoreRelation = new UserStoreRelation();
                userStoreRelation.setUserId(userId);
                userStoreRelation.setStoreId(store.getId());
                userStoreRelationService.add(userStoreRelation,userId+"");
            }
            store.setCookie(ksid);
            store.setStoreName(shopName);
            store.setServerId(pythonServerConfig.getServerId());
            store.setMobile(mobile);
            store.setOnlineStatus("ONLINE"); //设置为在线状态
            store.setRegionId(shopId);

            storeService.update(store.getId(),store,userId+"");
            meiTuanOperateService.upNotice(store.getId());
        }

        if(store != null){
            ElmeOperateServiceImpl.Query query = new ElmeOperateServiceImpl.Query();
            query.setShopId(store.getRegionId());
            query.setKsid(store.getCookie());
            query.setStoreId(store.getId());
            elmeOperateService.getAccessToken(query);
        }
    }

    @Data
    public static class unifiedorderAttachVOPro extends UnifiedorderAttachVO {
        private Long s;
        private Integer m;
        private String p;

    }

    public Store addBypassword(String username, String password,Long userId) {

//        List<Store> storeList = storeService.getList(new Search().add("username", SearchTypeEnum.EqualTo, username));
//        if(CollectionUtils.isNotEmpty(storeList)){
//            throw new BusinessException("该店铺已在您门下");
//        }

        Result result = meiTuanOperateService.loginByUsernamepassword(username, password);
        JSONObject jsonObject = JSONObject.parseObject(result.getData().toString());
        String cookie = jsonObject.getJSONObject("cookieInfo").getString("cookieStr");
        String ev_cookie = jsonObject.getJSONObject("cookieInfo").getString("ev_cookie");
        MeiTuanOperateServiceImpl.StoreInfo storeInfo = meiTuanOperateService.loginByCookie(cookie);
        String region_version = null;
        String region_id = null;
        JSONArray jsonArray = jsonObject.getJSONObject("cookieInfo").getJSONArray("cookie");
        for (Object obj : jsonArray) {
            JSONObject item = JSON.parseObject(obj.toString(), JSONObject.class);
            if("region_version".equals(item.getString("name"))){
                region_version=item.getString("value");
            }
            if("region_id".equals(item.getString("name"))){
                region_id=item.getString("value");
            }
        }
        Store selfStore = mtpassExsit(username, password, userId, cookie, ev_cookie, region_version, region_id);
        if (selfStore != null) return selfStore;

        Store store = new Store();
        store.setCookie(cookie);
        store.setEvaluateCookie(ev_cookie);
        store.setStoreName(storeInfo.getStoreName());
        store.setRegionId(region_id);
        store.setRegionVersion(region_version);
        store.setUsername(username);
        store.setPassword(password);
        store.setPlatform("MEITUAN");
        store.setExpireTime(DateUtils.addDays(new Date(),3)); //设置2天有效期
        store.setOnlineStatus("ONLINE"); //设置为在线状态
        store.setStoreStatus("1");
        storeService.add(store,userId+"");

        UserStoreRelation userStoreRelation = new UserStoreRelation();
        userStoreRelation.setUserId(userId);
        userStoreRelation.setStoreId(store.getId());
        userStoreRelationService.add(userStoreRelation,userId+"");

        Rule rule = new Rule();
        rule.setStoreId(store.getId());
        rule.setTime(4); //默认四分钟后出餐
        ruleService.add(rule,userId+"");
        meiTuanOperateService.upNotice(store.getId());
        return store;
    }

    @Resource
    RedisUtil redisUtil;

    @Override
    public void addCookieandStorage(String cookie, String storage,Long storeId) {
        redisUtil.addCookie(storeId,cookie);
        redisUtil.addStorage(storeId,storage);
    }

    private Store mtpassExsit(String username, String password, Long userId, String cookie, String ev_cookie, String region_version, String region_id) {
        //判断是否已经存在了该门店
        Store exStore = getStoreUninId(region_version);
        if(exStore != null){
            exStore.setCookie(cookie);
            exStore.setStoreName(meiTuanOperateService.loginByCookie(cookie).getStoreName());
            exStore.setRegionId(region_id);
            exStore.setEvaluateCookie(ev_cookie);
            exStore.setRegionVersion(region_version);
            exStore.setUsername(username);
            exStore.setPassword(password);
            exStore.setOnlineStatus("ONLINE"); //设置为在线状态
            storeService.update(exStore.getId(),exStore, userId +"");
            //判断它有没有这个门店
            Store selfStore = getStore(userId, exStore.getId());
            if(selfStore == null){ //他已经绑定了该门店
                UserStoreRelation userStoreRelation = new UserStoreRelation();
                userStoreRelation.setUserId(userId);
                userStoreRelation.setStoreId(exStore.getId());
                userStoreRelationService.add(userStoreRelation, userId +"");
            }
            meiTuanOperateService.upNotice(exStore.getId());
            return exStore;
        }
        return null;
    }

//    public static void main(String[] args) {
//        Date date = DateUtils.addDays(new Date(), 7);
//        System.out.println(DateUtils.dateTime(date));
//    }

    public void addTestStore(String storeName,Long userId){

        Store store = new Store();
//        store.setCookie(cookie);
//        store.setEvaluateCookie(ev_cookie);
        store.setStoreName(storeName);
//        store.setRegionId(region_id);
//        store.setRegionVersion(region_version);
//        store.setUsername(username);
//        store.setPassword(password);
        store.setOnlineStatus("ONLINE"); //设置为在线状态
        store.setStoreStatus("1");
        store.setExpireTime(DateUtils.addDays(new Date(),3));
        storeService.add(store,userId+"");

        UserStoreRelation userStoreRelation = new UserStoreRelation();
        userStoreRelation.setUserId(userId);
        userStoreRelation.setStoreId(store.getId());
        userStoreRelationService.add(userStoreRelation,userId+"");

        Rule rule = new Rule();
        rule.setStoreId(store.getId());
        rule.setTime(4); //默认四分钟后出餐
        ruleService.add(rule,userId+"");
        meiTuanOperateService.upNotice(store.getId());
    }



    public void sendCode(String mobile){
//        List<Store> storeList = storeService.getList(new Search().add("username", SearchTypeEnum.EqualTo, mobile));
//        if(CollectionUtils.isNotEmpty(storeList)){
//            throw new BusinessException("该店铺已在您门下");
//        }
        meiTuanOperateService.sendCode(mobile);
    }
    
    public Store loginByCookie(String cookie,Long userId){
        MeiTuanOperateServiceImpl.StoreInfo storeInfo = meiTuanOperateService.loginByCookie(cookie);
//        List<Store> storeList = storeService.getList(new Search().add("username", SearchTypeEnum.EqualTo, mobile));
//        if(CollectionUtils.isNotEmpty(storeList)){
//            throw new BusinessException("该店铺已在您门下");
//        }
        Store store = new Store();
        store.setCookie(cookie);
        store.setStoreName(storeInfo.getStoreName());
        store.setRegionId(storeInfo.getRegionId());
        store.setRegionVersion(storeInfo.getRegionVersion());
        store.setOnlineStatus("ONLINE"); //设置为在线状态
        store.setStoreStatus("1");
        storeService.add(store,userId+"");

        UserStoreRelation userStoreRelation = new UserStoreRelation();
        userStoreRelation.setUserId(userId);
        userStoreRelation.setStoreId(store.getId());
        userStoreRelationService.add(userStoreRelation,userId+"");

        Rule rule = new Rule();
        rule.setStoreId(store.getId());
        rule.setTime(4); //默认四分钟后出餐
        ruleService.add(rule,userId+"");
        return store;


    }


    public Store reloginByCookie(String cookie,Long userId,Long storeId){
        MeiTuanOperateServiceImpl.StoreInfo storeInfo = meiTuanOperateService.loginByCookie(cookie);
//        List<Store> storeList = storeService.getList(new Search().add("username", SearchTypeEnum.EqualTo, mobile));
//        if(CollectionUtils.isNotEmpty(storeList)){
//            throw new BusinessException("该店铺已在您门下");
//        }
        Store store = get(storeId);
        store.setCookie(cookie);
        store.setStoreName(storeInfo.getStoreName());
        store.setRegionId(storeInfo.getRegionId());
        store.setRegionVersion(storeInfo.getRegionVersion());
        store.setOnlineStatus("ONLINE"); //设置为在线状态
        store.setStoreStatus("1");
        storeService.update(storeId,store,userId+"");
        meiTuanOperateService.upNotice(store.getId());
        return store;


    }

    public Store loginByCode(String mobile,String code,Long userId){

        List<Store> storeList = storeService.getList(new Search().add("username", SearchTypeEnum.EqualTo, mobile));
//        if(CollectionUtils.isNotEmpty(storeList)){
//            throw new BusinessException("该店铺已在您门下");
//        }

        Result result = meiTuanOperateService.loginByCode(mobile, code);
        JSONObject jsonObject = JSONObject.parseObject(result.getData().toString());
        String storeName = jsonObject.getString("storeName");
        String cookie = jsonObject.getJSONObject("cookieInfo").getString("cookieStr");
        String ev_cookie = jsonObject.getJSONObject("cookieInfo").getString("ev_cookie");
        String region_version = null;
        String region_id = null;
        JSONArray jsonArray = jsonObject.getJSONObject("cookieInfo").getJSONArray("cookie");
        for (Object obj : jsonArray) {
            JSONObject item = JSON.parseObject(obj.toString(), JSONObject.class);
            if("region_version".equals(item.getString("name"))){
                region_version=item.getString("value");
            }
            if("region_id".equals(item.getString("name"))){
                region_id=item.getString("value");
            }
        }
        Store selfStore = meituanExsit(mobile, userId, cookie, ev_cookie, region_version, region_id);
        if (selfStore != null) return selfStore;
        Store store = new Store();
        store.setCookie(cookie);
        store.setStoreName(meiTuanOperateService.loginByCookie(cookie).getStoreName());
        store.setRegionId(region_id);
        store.setEvaluateCookie(ev_cookie);
        store.setRegionVersion(region_version);
        store.setMobile(mobile);
        store.setPlatform("MEITUAN");
        store.setExpireTime(DateUtils.addDays(new Date(),3)); //设置7天有效期
        store.setOnlineStatus("ONLINE"); //设置为在线状态
        store.setStoreStatus("1");
        storeService.add(store,userId+"");

        UserStoreRelation userStoreRelation = new UserStoreRelation();
        userStoreRelation.setUserId(userId);
        userStoreRelation.setStoreId(store.getId());
        userStoreRelationService.add(userStoreRelation,userId+"");

        Rule rule = new Rule();
        rule.setStoreId(store.getId());
        rule.setTime(4); //默认四分钟后出餐
        ruleService.add(rule,userId+"");
        meiTuanOperateService.upNotice(store.getId());
        return store;
    }

    private Store meituanExsit(String mobile, Long userId, String cookie, String ev_cookie, String region_version, String region_id) {
        //判断是否已经存在了该门店
        Store exStore = getStoreUninId(region_version);
        if(exStore != null){
            exStore.setCookie(cookie);
            exStore.setStoreName(meiTuanOperateService.loginByCookie(cookie).getStoreName());
            exStore.setRegionId(region_id);
            exStore.setEvaluateCookie(ev_cookie);
            exStore.setRegionVersion(region_version);
            exStore.setMobile(mobile);
            exStore.setPlatform("MEITUAN");
            exStore.setOnlineStatus("ONLINE"); //设置为在线状态
            storeService.update(exStore.getId(),exStore, userId +"");
            //判断它有没有绑定这个门店
            Store selfStore = getStore(userId, exStore.getId());
            if(selfStore == null){
                UserStoreRelation userStoreRelation = new UserStoreRelation();
                userStoreRelation.setUserId(userId);
                userStoreRelation.setStoreId(exStore.getId());
                userStoreRelationService.add(userStoreRelation, userId +"");
            }
            meiTuanOperateService.upNotice(exStore.getId());
            return exStore;
        }
        return null;
    }


    //重新通过账号密码登录
    public Store reloginBypassword(String username, String password,Long userId,Long storeId) {


        Result result = meiTuanOperateService.loginByUsernamepassword(username, password);
        JSONObject jsonObject = JSONObject.parseObject(result.getData().toString());
        String storeName = jsonObject.getString("storeName");
        String cookie = jsonObject.getJSONObject("cookieInfo").getString("cookieStr");
        String ev_cookie = jsonObject.getJSONObject("cookieInfo").getString("ev_cookie");
        String region_version = null;
        String region_id = null;
        JSONArray jsonArray = jsonObject.getJSONObject("cookieInfo").getJSONArray("cookie");
        for (Object obj : jsonArray) {
            JSONObject item = JSON.parseObject(obj.toString(), JSONObject.class);
            if("region_version".equals(item.getString("name"))){
                region_version=item.getString("value");
            }
            if("region_id".equals(item.getString("name"))){
                region_id=item.getString("value");
            }
        }
        Store store = get(storeId);
        store.setCookie(cookie);
        store.setStoreName(meiTuanOperateService.loginByCookie(cookie).getStoreName());
        store.setRegionId(region_id);
        store.setEvaluateCookie(ev_cookie);
        store.setRegionVersion(region_version);
        store.setUsername(username);
        store.setPassword(password);
        store.setOnlineStatus("ONLINE"); //设置为在线状态
        store.setStoreStatus("1");
        storeService.update(storeId,store,userId+"");
        meiTuanOperateService.upNotice(store.getId());
        return store;
    }


    public Store reloginByCode(String mobile,String code,Long userId,Long storeId){

        List<Store> storeList = storeService.getList(new Search().add("username", SearchTypeEnum.EqualTo, mobile));
        if(CollectionUtils.isNotEmpty(storeList)){
            throw new BusinessException("该店铺已在您门下");
        }

        Result result = meiTuanOperateService.loginByCode(mobile, code);
        JSONObject jsonObject = JSONObject.parseObject(result.getData().toString());
        String storeName = jsonObject.getString("storeName");
        String cookie = jsonObject.getJSONObject("cookieInfo").getString("cookieStr");
        String ev_cookie = jsonObject.getJSONObject("cookieInfo").getString("ev_cookie");
        String region_version = null;
        String region_id = null;
        JSONArray jsonArray = jsonObject.getJSONObject("cookieInfo").getJSONArray("cookie");
        for (Object obj : jsonArray) {
            JSONObject item = JSON.parseObject(obj.toString(), JSONObject.class);
            if("region_version".equals(item.getString("name"))){
                region_version=item.getString("value");
            }
            if("region_id".equals(item.getString("name"))){
                region_id=item.getString("value");
            }
        }
        Store store = get(storeId);
        store.setCookie(cookie);
        store.setStoreName(meiTuanOperateService.loginByCookie(cookie).getStoreName());
        store.setRegionId(region_id);
        store.setRegionVersion(region_version);
        store.setEvaluateCookie(ev_cookie);
        store.setMobile(mobile);
        store.setOnlineStatus("ONLINE"); //设置为在线状态
        store.setStoreStatus("1");
        storeService.update(storeId,store,userId+"");
        meiTuanOperateService.upNotice(store.getId());
        return store;
    }




    @Resource
    StoreMapper storeMapper;

    public List<Store> getStoreList(Long userId,String onlineStatus,String storeStatus){

        return storeMapper.getStoreList(userId,onlineStatus,storeStatus);
    }



    public Store getStore(Long userId , Long storeId){
        List<UserStoreRelation> list = userStoreRelationService.getList(new Search().add("userId", SearchTypeEnum.EqualTo, userId)
                .add("storeId", SearchTypeEnum.EqualTo, storeId));
        if(CollectionUtils.isNotEmpty(list)){
            UserStoreRelation userStoreRelation = list.get(0);
            Store store = storeService.get(userStoreRelation.getStoreId());
            return store;
        }else{
            return null;
        }
    }

    public Store getStoreUninId(String uninId){
        List<Store> storeList = this.getList(new Search().add("regionVersion", SearchTypeEnum.EqualTo, uninId));
        if(CollectionUtils.isNotEmpty(storeList)){
            return storeList.get(0);
        }else{
            storeList = this.getList(new Search().add("regionId", SearchTypeEnum.EqualTo, uninId));
            if(CollectionUtils.isNotEmpty(storeList)){
                return storeList.get(0);
            }
        }
        return null;
    }
    @Resource
    ElmeOperateServiceImpl elmeOperateService;

    //饿了么账号密码登录
    public Store loginByEleme(String username,String password,Long userId){

        Result result = elmeOperateService.loginByUsernamepassword(username, password);
        if(!result.isSuccess()){
            throw new BusinessException(result.getMessage());
        }
        AutoReLoginTask.Res storage = JSON.parseObject(JSON.toJSONString(result.getData()), AutoReLoginTask.Res.class);
        Store selfStore = isExsit(username, password, userId, storage);
        if (selfStore != null) return selfStore;
        Store store = new Store();
        store.setCookie(storage.getStorage().getKsid());

        store.setStoreName(storage.getStorage().getShopName());
        store.setRegionId(storage.getStorage().getShopId());
        store.setUsername(username);
        store.setPlatform("ELEME");
        store.setPassword(password);
        store.setExpireTime(DateUtils.addDays(new Date(),3)); //设置7天有效期
        store.setOnlineStatus("ONLINE"); //设置为在线状态
        store.setStoreStatus("1");
        storeService.add(store,userId+"");

        UserStoreRelation userStoreRelation = new UserStoreRelation();
        userStoreRelation.setUserId(userId);
        userStoreRelation.setStoreId(store.getId());
        userStoreRelationService.add(userStoreRelation,userId+"");

        Rule rule = new Rule();
        rule.setStoreId(store.getId());
        rule.setTime(4); //默认四分钟后出餐
        ruleService.add(rule,userId+"");
        meiTuanOperateService.upNotice(store.getId());
        return store;
    }

    private Store isExsit(String username, String password, Long userId, AutoReLoginTask.Res storage) {
        //判断是否已经存在了该门店
        Store exStore = getStoreUninId(storage.getStorage().getShopId());
        if(exStore != null){
            exStore.setCookie(storage.getStorage().getKsid());
            exStore.setStoreName(storage.getStorage().getShopName());
            exStore.setRegionId(storage.getStorage().getShopId());
            exStore.setUsername(username);
            exStore.setPlatform("ELEME");
            exStore.setPassword(password);
            exStore.setExpireTime(DateUtils.addDays(new Date(),3)); //设置7天有效期
            exStore.setOnlineStatus("ONLINE"); //设置为在线状态
            exStore.setStoreStatus("1");
            storeService.update(exStore.getId(),exStore, userId +"");
            Store selfStore = getStore(userId, exStore.getId());
            if(selfStore == null){ //他已经绑定了该门店
                UserStoreRelation userStoreRelation = new UserStoreRelation();
                userStoreRelation.setUserId(userId);
                userStoreRelation.setStoreId(selfStore.getId());
                userStoreRelationService.add(userStoreRelation, userId +"");
            }
            meiTuanOperateService.upNotice(selfStore.getId());
            return selfStore;
        }
        return null;
    }


    //饿了么验证码登录
    public Store loginByCode(String code,Long userId,String username,String password){
        Result result = elmeOperateService.loginByCode(code);
        if(!result.isSuccess()){
            throw new BusinessException(result.getMessage());
        }
        AutoReLoginTask.Res storage = JSON.parseObject(JSON.toJSONString(result.getData()), AutoReLoginTask.Res.class);
        Store selfStore = isExsit(username, password, userId, storage);
        if (selfStore != null) return selfStore;
        Store store = new Store();
        store.setCookie(storage.getStorage().getKsid());

        store.setStoreName(storage.getStorage().getShopName());
        store.setRegionId(storage.getStorage().getShopId());
        store.setUsername(username);
        store.setPlatform("ELEME");
        store.setPassword(password);
        store.setExpireTime(DateUtils.addDays(new Date(),3)); //设置7天有效期
        store.setOnlineStatus("ONLINE"); //设置为在线状态
        store.setStoreStatus("1");
        storeService.add(store,userId+"");

        UserStoreRelation userStoreRelation = new UserStoreRelation();
        userStoreRelation.setUserId(userId);
        userStoreRelation.setStoreId(store.getId());
        userStoreRelationService.add(userStoreRelation,userId+"");

        Rule rule = new Rule();
        rule.setStoreId(store.getId());
        rule.setTime(4); //默认四分钟后出餐
        ruleService.add(rule,userId+"");
        meiTuanOperateService.upNotice(store.getId());
        return store;
    }

}
